home *** CD-ROM | disk | FTP | other *** search
/ The Original Shareware 1.1 / The Original Shareware (WeMake CDs)(Volume 1.1)(CDs, Inc)(1993).iso / 35 / os2frtn.zip / FORTUNE.C next >
C/C++ Source or Header  |  1990-01-17  |  2KB  |  92 lines

  1. /*% cc -O -K -i -s -o fortune %
  2. */
  3. /*
  4.  * Fetch a fortune from the Fortunes file by randomly seeking
  5.  *  within that file and then searching for the Nth next fortune,
  6.  *  ( 0 <= N <= 15).   If EOF is reached, rewind and continue.
  7.  *  This two step process minimizes file i/o while making the frequency
  8.  *  of each fortune realtively independent of the size of its predecessors.
  9.  *
  10.  * Display the selected fortune, replacing @ characters with newlines.
  11.  * This format (single line fortunes) allows foreign fortunes to be
  12.  * merged into a local file with common lines deleted by sort -u
  13.  *
  14.  * If called with any argument, repeat until killed.
  15.  *
  16.  */
  17. #include <stdio.h>
  18. #include <sys/types.h>
  19. #include <sys/stat.h>
  20.  
  21. char *Fortunes = "fortunes";
  22.  
  23. #define LEN 2048
  24. char line[LEN];
  25.  
  26. main(argc, argv)
  27. char **argv;
  28. {
  29.     long p;
  30.     register l;
  31.     register char *q;
  32.     time_t t;
  33.     FILE *f;
  34.     struct stat sbuf;
  35.     char *fortenv;
  36.  
  37.     if ( (fortenv = getenv ("FORTUNES")) != NULL )
  38.         Fortunes = fortenv;
  39.         
  40.     if (argc >= 3 && !strcmp(argv[1], "-f")) {
  41.         Fortunes = argv[2]; argv += 2; argc -= 2;
  42.     }
  43.     f = fopen(Fortunes, "r");
  44.     if (f == NULL) {
  45.         write(1,"Memory fault -- core dumped\n", 29);
  46.         exit(1);
  47.     }
  48.     time(&t);
  49.     srand(getpid() ^ (int)((t>>16) ^ t));
  50.     fstat(fileno(f), &sbuf);
  51.     do {
  52.         p = rand() % sbuf.st_size;
  53.         fseek(f, p, 0);
  54.         for (l=((rand())&07); l-- >= 0; ) {
  55.             fgets(line, LEN, f);
  56.             if (fgets(line, LEN, f) == NULL || line[0] == 0) {
  57.                 rewind(f);
  58.                 fgets(line, LEN, f);
  59.             }
  60.         }
  61.         for(q = line; *q++;)
  62.             if ( *q  == '@')
  63.                 *q = '\n';
  64.         l = (q - line) -1;
  65.         write(1, line, l);
  66.     } while (argc > 1);
  67.     exit(0);
  68. }
  69.  
  70. char *
  71. fgets(s, n, f)
  72. register char *s;
  73. register n;
  74. FILE *f;
  75. {
  76.     register c;
  77.     register char *p;
  78.  
  79.     p=s;
  80.     while (--n>0) {
  81.         if ((c = getc(f)) == EOF)
  82.             break;
  83.         if ((*s++ = c) == '\n')
  84.             break;
  85.     }
  86.     *s = 0;
  87.     if (p == s)
  88.         return NULL;
  89.     return p;
  90. }
  91.  
  92.